package com.peng.herostory;

import com.google.protobuf.GeneratedMessageV3;
import com.peng.herostory.model.UserManager;
import com.peng.herostory.msg.GameMsgProtocol;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.AttributeKey;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class GameChannelHandler extends SimpleChannelInboundHandler<GeneratedMessageV3> {


    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
        Broadcaster.addClient(ctx.channel());
    }

    /**
     * 客户端退出
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        super.handlerRemoved(ctx);
        Integer userId = (Integer) ctx.channel().attr(AttributeKey.valueOf("userId")).get();
        if (userId == null) {
            log.info("userId为空");
            return;
        }
        UserManager.removeUserById(userId);
        Broadcaster.removeClient(ctx.channel());
        GameMsgProtocol.UserQuitResult quitResult = GameMsgProtocol.UserQuitResult.newBuilder().setQuitUserId(userId).build();
        Broadcaster.broadcast(quitResult);

    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, GeneratedMessageV3 msg) throws Exception {
        MainThreadProcessor.getInstance().process(ctx, msg);
    }


}
